﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BEGDC.PreContract.BLL;

namespace PreContractWeb.Administration
{
    public partial class EditDetailProvince : System.Web.UI.Page
    {
        private BEGDC.PreContract.BLL.Authentication.PCIdentity user;

        protected void Page_Load(object sender, EventArgs e)
        {
           
            user = new BEGDC.PreContract.BLL.Authentication.PCIdentity(HttpContext.Current.User.Identity);
            Page.Header.Controls.Add(new LiteralControl(@"<base target=""_self"" />"));
            if (!ReportHelper.IsAdmin(user.EmployeeId))
            {
                this.divError.InnerHtml = AlertMessage.NoAdminPermission;
                this.divConnect.Visible = false;
                this.divError.Visible = true;
            }

            else if (!IsPostBack)
            {
                if (Request["id"] != null)
                    if (Request["id"] == "-1")
                    {
                        this.SaveButton.Text = "添加(Add)";
                        this.CNTitleLabel.Text = "添加省份";
                        this.ENTitleLabel.Text = "Add A Province";
                    }
                    else
                    {
                        this.SaveButton.Text = "保存(Save)";
                        this.CNTitleLabel.Text = "编辑省份信息";
                        this.ENTitleLabel.Text = "Edit Province Information";
                        this.LoadData();
                    }

                Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }
        }

        protected void LoadData()
        {
            try
            {
                short provinceID = short.Parse(Request["id"].ToString());

                BEGDC.PreContract.BLL.IProvince iProvince = (BEGDC.PreContract.BLL.IProvince)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Province_Service];
                BEGDC.PreContract.DAL.Province province = iProvince.GetProvince(provinceID);

                this.CNameTextBox.Text = province.ProvinceCName;
                this.ENameTextBox.Text = province.ProvinceEName;
                this.SortNumberTextBox.Text = province.SortNumber.ToString();
                this.ProvinceCodeTextBox.Text = province.ProvinceCode;
                this.ActiveCheckBox.Checked = province.Active;
                //Joan 2008-10-20 date label format
                DateTime date;
                if (province.CreateDate != Nullables.NullableDateTime.Default)
                {
                    date = System.Convert.ToDateTime(province.CreateDate.Value);
                    this.CreateTimeLabel.Text = date.ToString("yyyy-MM-dd") + " " + date.ToShortTimeString();
                }

                if (province.UpdateDate != Nullables.NullableDateTime.Default)
                {
                    date = System.Convert.ToDateTime(province.UpdateDate.Value);
                    this.UpdateTimeLabel.Text = date.ToString("yyyy-MM-dd") + " " + date.ToShortTimeString();
                }

                //this.CreateTimeLabel.Text = province.CreateDate.ToString();
                //this.UpdateTimeLabel.Text = province.UpdateDate.ToString();
                //end

                //yuliang 2010-5-15
                BaseFunction.BindClusterDropDownList(ddlCluster, string.Empty, true);
                this.ddlCluster.SelectedIndex = ddlCluster.Items.IndexOf(ddlCluster.Items.FindByValue(province.ClusterID.ToString()));
            }

            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
 
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                short provinceID = short.Parse(Request["id"].ToString());
                bool flag = true;
                BEGDC.PreContract.BLL.IProvince iProvince = (BEGDC.PreContract.BLL.IProvince)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Province_Service];

                if (this.IsProvinceCodeExist(this.ProvinceCodeTextBox.Text.Trim(), provinceID.ToString()))
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + BaseFunction.ChangeAlertMessage(AlertMessage.ExistedRecord) + "')</script>");
                    return;
                }

                if (this.IsSortNumberExist(this.SortNumberTextBox.Text.Trim(), provinceID.ToString()))
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + BaseFunction.ChangeAlertMessage(AlertMessage.HasSortNumber) + "')</script>");
                    return;
                }

                if (this.ddlCluster.SelectedIndex < 0)
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择大区！')</script>");
                    return;
                }

                //
                if (provinceID == -1)
                {
                    if (this.IsProvinceCodeExist(this.ProvinceCodeTextBox.Text.Trim(),String.Empty))
                    {
                        this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + BaseFunction.ChangeAlertMessage(AlertMessage.ExistedRecord) + "')</script>");
                        return;
                    }

                    int numflag = iProvince.AddProvince(this.ProvinceCodeTextBox.Text.Trim(), this.ENameTextBox.Text.Trim(), this.CNameTextBox.Text.Trim(),
                                         Convert.ToInt32(this.SortNumberTextBox.Text.Trim()), DateTime.Now, DateTime.Now,this.ActiveCheckBox.Checked,int.Parse(this.ddlCluster.SelectedItem.Value));
                    if (numflag == 0)
                        flag = false;
                }
                else
                {
                    

                    BEGDC.PreContract.DAL.Province province = iProvince.GetProvince(provinceID);

                    flag = iProvince.UpdateProvince(province.ProvinceID, this.ProvinceCodeTextBox.Text.Trim(), this.ENameTextBox.Text.Trim(), this.CNameTextBox.Text.Trim(),
                                         Convert.ToInt32(this.SortNumberTextBox.Text.Trim()), province.CreateDate, DateTime.Now, this.ActiveCheckBox.Checked, int.Parse(this.ddlCluster.SelectedItem.Value));
                }

                if (!flag)
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + AlertMessage.ExistedRecord + "')</script>");
                    return;
                }
                this.Response.Write("<script language='javascript'>alert('" + BaseFunction.ChangeAlertMessage(AlertMessage.OperationSuccess) + "');var arr=new Array(); arr[0]=0; window.returnValue=arr;window.close();</script>");
                
            }
            catch (Exception ex)
           {
               this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
           }
        }

        protected bool IsProvinceCodeExist(string proviceCode,string provinceID)
        {
            string condtion = String.Format("ProvinceCode = '{0}'", proviceCode);

            if(!provinceID.Equals(String.Empty))
                condtion += String.Format("AND ProvinceID <> {0}",provinceID); 
            
            BEGDC.PreContract.BLL.IProvince iProvince = (BEGDC.PreContract.BLL.IProvince)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Province_Service];
                DataTable dt = iProvince.GetProvince_DataTable(condtion);

                if (dt.Rows.Count == 0)
                    return false;
                else
                    return true;
            
        }

        protected bool IsSortNumberExist(string sortNumber, string provinceID)
        {
            string condition = String.Format("SortNumber = '{0}'", sortNumber);

            if (!provinceID.Equals(String.Empty))
                condition += String.Format(" AND ProvinceID <> {0}", provinceID);

            BEGDC.PreContract.BLL.IBG iBG = (BEGDC.PreContract.BLL.IBG)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_BG_Service];

            BEGDC.PreContract.BLL.IProvince iProvince = (BEGDC.PreContract.BLL.IProvince)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Province_Service];
            DataTable dt = iProvince.GetProvince_DataTable(condition);

            if (dt.Rows.Count == 0)
                return false;
            else
                return true;
        }
    }
}
